const os = require('os')
const si = require('systeminformation')
const WebSocket = require('ws');
var config = require("./go.json")

function connect() {
    var ws = new WebSocket(config.WsServer);
    var timer;
    ws.on('open', function open() {
        timer = setInterval(() => {
            async function net() {
                //console.log(os.loadavg())
                var data = await si.networkStats();
                //var cpu_data = await si.currentLoad();
                //console.log(cpu_data)
                for (let i = 0; i < data.length; i++) {
                    if (data[i].iface == config["TargetNet"]) {
                        let sys_info = {
                            token: config["Token"],
                            mem: Math.floor((os.freemem()) / (1024 * 1024)),
                            rx: 0 | (data[0].rx_sec / 1024),
                            tx: 0 | (data[0].tx_sec / 1024),
                            time: Math.floor(Date.now() / 1000)
                        }
                        //kb
                        ws.send(JSON.stringify(sys_info));
                    }
                }
            };
            net();
        }, 1000);
    });

    // ws.on('message', function incoming(data) {
    //     console.log(data);
    // });
    ws.on('error', function () {
        console.log('socket error');
        //setTimeout(connect, 1000);
    });
    ws.on('close', function () {
        console.log('socket close');
        ws.terminate();
        clearInterval(timer);
        connect()
    });
}
connect();